import random
import string
#鉴权
from django.core.cache import cache
from django.core.signing import Signer
from datetime import timedelta
#分页
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from .models import userInfo,Track,PlayRecord
# Create your views here.
#登录
@api_view(['POST'])
def login(request):
    data=JSONParser().parse(request)
    id=data.get('id')
    username=data.get('username')
    password=data.get('password')
    obj=userInfo.objects.filter(id=id)
    obj.username=username
    obj.password=password
    return JsonResponse({
        'code':200,
        'msg':'登录成功'
    })
#列表页面
#非空验证
def luoji(n):
    return n is None or str(n).strip()==''
@api_view(['POST'])
def reg(request):
    data=JSONParser().parse(request)
    play_times=data['play_times']
    track_id=data['track_id']
    user_id=data['user_id']
    if luoji(play_times):
        return JsonResponse({
            'code':404,
            'msg':'参数不能为空'
        })
    PlayRecord(play_times=play_times,track_id_id=track_id,user_id_id=user_id).save()
    return JsonResponse({
        'code':200,
        'msg':'点播成功'
    })

# #产生token
# def createtoken(name):
#     randomstr=''.join(random.choice(string.ascii_letters,k=8))
#     token=Signer().sign(randomstr+name)
#     cache.set(f'test_{name}',token,timeout=timedelta(minutes=100).total_seconds())
#     return token




























#分页

#查询
@api_view(['GET'])
def chaxun(request):
    datas=PlayRecord.objects.filter()
    lis=[]
    for data in datas:
        lis.append({
            '曲目名称':data.track_id_id,
            '用户名':data.user_id_id,
            '播放次数':data.play_times,
            '播放日期':data.play_date,
        })
    return JsonResponse({
        'code':200,
        'msg':'查询成功',
        'data':lis
    })






@api_view(['GET'])
def pagedata(request):
    #获取页面
    page=request.GET.get('page')
    #获取每页数据
    pagesize=request.GET.get('pagesize')
    #获取表中所有数据
    alldata=PlayRecord.objects.filter().values()
    #分页设置
    pageobj=Paginator(alldata,pagesize)
    try:
        aa=pageobj.page(page)
    except EmptyPage:
        aa=pageobj.page(pageobj.num_pages)
    except PageNotAnInteger:
        aa=pageobj.page(1)
    lis=[]
    for item in pageobj.object_list:
        lis.append({
            '播放次数':item.play_times
        })
    return JsonResponse({
        'code':200,
        'msg':'查询成功',
        'data':lis,
        'page':{
            'page':page,
            'pagesize':pagesize,
            'count':alldata.count()
        }
    })

